﻿namespace LeadMaster.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using LeadMaster.Models;
    using LeadMaster.DAL;
    using LeadMaster.ViewModels;
    using System.Data.Entity.Core;

    public class OrdersController : Controller
    {
        private DunsmoreContext db = new DunsmoreContext();

        public ActionResult Index()
        {
            var orders = db.Orders.Include(o => o.ScheduleTemplate)
                        .Include(o => o.Invoicing)
                        .Include(o => o.PaymentTerms)
                        .Include(o => o.OrderStatus)
                        .Include(o => o.LeadsReplacement)
                        .Include(o => o.FrameworkAgreement);

            return PartialView(orders.ToList());
        }

        public ActionResult IndexPending()
        {
            var orders = db.Orders.Include(o => o.ScheduleTemplate)
                        .Include(o => o.Invoicing)
                        .Include(o => o.PaymentTerms)
                        .Include(o => o.OrderStatus)
                        .Include(o => o.LeadsReplacement);

            return View(orders.ToList());
        }

        public ActionResult Details(int id = 0)
        {
            Orders orders = db.Orders.Find(id);
            if (orders == null)
            {
                return HttpNotFound();
            }
            return View(orders);
        }

        //
        // GET: /Orders/Create

        public ActionResult Create()
        {
            ViewBag.ScheduleTemplateID = new SelectList(db.ScheduleTemplate, "ScheduleTemplateID", "Title");
            ViewBag.InvoicingID = new SelectList(db.Invoicing, "InvoicingID", "Title");
            ViewBag.PaymentTermsID = new SelectList(db.PaymentTerms, "PaymentTermsID", "Title");
            ViewBag.Order_LeadsReplacementID = new SelectList(db.LeadsReplacement, "LeadsReplacementID", "Title");
            ViewBag.FrameworkAgreementID = new SelectList(db.FrameworkAgreements, "FrameworkAgreementID", "Title");
            ViewBag.CompanyID = new SelectList(db.Companies.Where(m => m.Category == "O"), "CompanyID", "Company");
            ViewBag.OrderStatusID = new SelectList(db.OrderStatus.OrderBy(m => m.DisplayOrder), "OrderStatusID", "OrderStatusDescription");
            ViewModels.ViewModelOrders viewModel = new ViewModels.ViewModelOrders();
            viewModel.ScheduleSections = db.ScheduleSection.Where(m => m.Category == "M").OrderBy(m => m.ScheduleSectionsID).ToList();
            viewModel.SectionMergeText = new string[viewModel.ScheduleSections.Count];
            viewModel.newFee = new Fees();
            viewModel.TheFees.Add(viewModel.newFee);
            return PartialView(viewModel);
        }

        [HttpPost]
        public ActionResult Create(ViewModelOrders viewModel)
        {
            int lineNumber = 74;
            try
            {
                if (ModelState.IsValid)
                {
                    db.Orders.Add(viewModel.Order);
                    db.SaveChanges();
                    lineNumber= 81;
                    viewModel.OrderSection = new OrderSections();
                    int iCounter = 0;
                    foreach (ScheduleSection scheduleSection in viewModel.ScheduleSections)
                    {
                        OrderSections newSection = new OrderSections();
                        newSection.ScheduleSectionsID = scheduleSection.ScheduleSectionsID;
                        newSection.ReplacementHeader = scheduleSection.FieldHeader;
                        newSection.Content = viewModel.SectionMergeText[iCounter];
                        newSection.OrderID = viewModel.Order.OrderID;
                        db.OrderSections.Add(newSection);
                        iCounter++;
                    }
                    lineNumber= 94;
                    // save the fees
                    iCounter = 0;
                    foreach (Fees item in viewModel.TheFees)
                    {
                        item.OrderID = viewModel.Order.OrderID;
                        db.Fees.Add(item);
                    }
                    lineNumber= 102;
                    viewModel.Order.OrderStatusID = 3;
                    db.SaveChanges();
                    lineNumber= 105;
                    return RedirectToAction("Index");
                }
            }
            catch (Exception ex)
            {
                //ViewBag.ScheduleTemplateID = new SelectList(db.ScheduleTemplate, "ScheduleTemplateID", "HeaderText", viewModel.Order.ScheduleTemplateID);
                //ViewBag.InvoicingID = new SelectList(db.Invoicing, "InvoicingID", "Title", viewModel.Order.InvoicingID);
                //ViewBag.PaymentTermsID = new SelectList(db.PaymentTerms, "PaymentTermsID", "Description", viewModel.Order.PaymentTermsID);
                //ViewBag.LeadsReplacementID = new SelectList(db.LeadsReplacement, "LeadsReplacementID", "Title");
                //return View(viewModel);
                ViewBag.ErrorMessage = lineNumber.ToString() + " : " + ex.Message;
                
                return View("Errormessages");

            }
            return RedirectToAction("Index");
        }

        public ActionResult AddFee(string id)
        {
            ViewModelOrders viewModel = new ViewModelOrders();
            viewModel.FeeCounter = Convert.ToInt32(id);
            int feeCounter = Convert.ToInt32(id);
            viewModel.newFee = new Fees();
            while (feeCounter >= 0)
            {
                viewModel.TheFees.Add(viewModel.newFee);
                feeCounter--;
            }
            return PartialView("Fee", viewModel);
        }

        public ActionResult ReplaceTemplate(string id)
        {
            int scheduleTemplateID = Convert.ToInt32(id);
            ViewModels.ViewModelOrders viewModel = new ViewModels.ViewModelOrders();
            var sections = from s in db.ScheduleSection
                           join t in db.ScheduleTemplateSection on s.ScheduleSectionsID equals t.ScheduleSectionsID
                           where t.ScheduleTemplateID == scheduleTemplateID
                           orderby t.DisplayOrder
                           select s;
            viewModel.ScheduleSections = sections.ToList();

            return PartialView("Templates", viewModel);
        }

        public ActionResult Edit(int id = 0)
        {
            ViewModels.ViewModelOrders viewModel = new ViewModels.ViewModelOrders();
            viewModel.Order = db.Orders.Find(id);
            if (viewModel.Order == null)
            {
                return HttpNotFound();
            }
            ViewBag.ScheduleTemplateID = new SelectList(db.ScheduleTemplate, "ScheduleTemplateID", "Title");
            ViewBag.InvoicingID = new SelectList(db.Invoicing, "InvoicingID", "Title");
            ViewBag.PaymentTermsID = new SelectList(db.PaymentTerms, "PaymentTermsID", "Title");
            ViewBag.Order_LeadsReplacementID = new SelectList(db.LeadsReplacement, "LeadsReplacementID", "Title");
            ViewBag.FrameworkAgreementID = new SelectList(db.FrameworkAgreements, "FrameworkAgreementID", "Title");
            ViewBag.CompanyID = new SelectList(db.Companies.Where(m => m.Category == "O"), "CompanyID", "Company");
            viewModel.ScheduleSections = db.ScheduleSection.Where(m => m.Category == "M").OrderBy(m => m.ScheduleSectionsID).ToList();
            viewModel.SectionMergeText = new string[viewModel.ScheduleSections.Count];
            viewModel.TheFees = db.Fees.Where(m => m.OrderID == id).ToList();
            viewModel.OrderSections = db.OrderSections.Where(m => m.OrderID == id).OrderBy(m => m.ScheduleSectionsID).ToList();
            ViewBag.OrderStatusID = new SelectList(db.OrderStatus.OrderBy(m => m.DisplayOrder), "OrderStatusID", "OrderStatusDescription");
            return PartialView(viewModel);
        }

        [HttpPost]
        public ActionResult Edit(ViewModelOrders viewModel)
        {
            if (ModelState.IsValid)
            {
                Orders order = db.Orders.Find(viewModel.Order.OrderID);
                order.CompanyID = viewModel.Order.CompanyID;
                order.FrameworkAgreementID = viewModel.Order.FrameworkAgreementID;
                order.InvoicingID = viewModel.Order.InvoicingID;
                order.LeadsReplacementID = viewModel.Order.LeadsReplacementID;
                order.Guarantee = viewModel.Order.Guarantee;
                order.PaymentTermsID = viewModel.Order.PaymentTermsID;
                order.Title = viewModel.Order.Title;
                order.FeesOther = viewModel.Order.FeesOther;
                order.OrderStatusID = viewModel.Order.OrderStatusID;
                order.ScheduleTemplateID = viewModel.Order.ScheduleTemplateID;
                db.Entry(order).State = EntityState.Modified;
                db.SaveChanges();
                int iCounter = 0;
                if (viewModel.OrderSections == null)
                {
                    // remove any existing OrderSections in there for this order
                    List<OrderSections> currentSavedOrderSections = db.OrderSections.Where(m => m.OrderID == viewModel.Order.OrderID).ToList();
                    foreach (OrderSections orderSection in currentSavedOrderSections)
                    {
                        OrderSections deletedOrderSection = new OrderSections();
                        deletedOrderSection = db.OrderSections.Find(orderSection.OrderSectionsID);
                        db.OrderSections.Remove(deletedOrderSection);
                    }
                    // now to save the new selection to the OrderSection table
                    viewModel.OrderSection = new OrderSections();
                    foreach (ScheduleSection scheduleSection in viewModel.ScheduleSections)
                    {
                        OrderSections newSection = new OrderSections();
                        newSection.ScheduleSectionsID = scheduleSection.ScheduleSectionsID;
                        newSection.ReplacementHeader = scheduleSection.FieldHeader;
                        newSection.Content = viewModel.SectionMergeText[iCounter];
                        newSection.OrderID = viewModel.Order.OrderID;
                        db.OrderSections.Add(newSection);
                        iCounter++;
                    }
                }
                else
                {
                    // changes original sections
                    foreach (OrderSections orderSection in viewModel.OrderSections)
                    {
                        OrderSections oS = db.OrderSections.Find(orderSection.OrderSectionsID);
                        oS.ReplacementHeader = orderSection.ReplacementHeader;
                        oS.Content = orderSection.Content;
                        db.Entry(oS).State = EntityState.Modified;
                    }
                }
                // Now to save the Fees
                iCounter = 0;
                foreach (Fees item in viewModel.TheFees)
                {
                    if (item.FeesID==0)
                    {
                        item.OrderID = viewModel.Order.OrderID;
                        db.Fees.Add(item);
                    }
                    else
                    {
                        Fees currentFee = new Fees();
                        currentFee = db.Fees.Find(item.FeesID);
                        currentFee.Description = item.Description;
                        currentFee.Quantity = item.Quantity;
                        currentFee.PriceEach = item.PriceEach;
                        db.Entry(currentFee).State = EntityState.Modified;
                    }
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return RedirectToAction("Index");
        }

        //
        // GET: /Orders/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Orders orders = db.Orders.Find(id);
            if (orders == null)
            {
                return HttpNotFound();
            }
            return View(orders);
        }

        //
        // POST: /Orders/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Orders orders = db.Orders.Find(id);
            db.Orders.Remove(orders);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}